package com.chinawayltd.ews.sample.web.main;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chinawayltd.ews.sample.manager.redis.MainAndMonitorDateManager;
import com.chinawayltd.ews.sample.model.order.OrderDetailVO;
import com.chinawayltd.ews.sample.model.order.OrderVO;
import com.chinawayltd.ews.sample.model.task.TaskBranchVO;
import com.chinawayltd.ews.sample.model.task.TaskDetailVO;
import com.chinawayltd.ews.sample.model.task.TaskEventVO;
import com.chinawayltd.ews.sample.model.task.TaskMaterielVO;
import com.chinawayltd.ews.sample.model.task.TaskNodeVO;
import com.chinawayltd.ews.sample.model.task.TaskScreenVO;
import com.chinawayltd.ews.sample.model.task.TaskVO;
import com.chinawayltd.ews.sample.service.main.MainService;
import com.chinawayltd.ews.sample.service.order.OrderService;
import com.chinawayltd.ews.sample.service.task.TaskEventService;
import com.chinawayltd.ews.sample.service.task.TaskNodeService;
import com.chinawayltd.ews.sample.service.task.TaskService;
import com.chinawayltd.ews.sample.util.BaseController;
import com.chinawayltd.ews.sample.util.ResultModel;
import com.chinawayltd.ews.sample.web.query.TaskGirdQuery;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;

/**
 * @program: greeProject
 * @description 首页和监控大屏
 * @author: chenxin
 * @create: 2018年5月12日 下午7:43:03
 */
@Api(tags = { "首页和监控大屏调用接口" })
@RestController
@RequestMapping(value = "/web/main")
public class MainController extends BaseController{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private MainService mainService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private TaskEventService taskEventService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private TaskNodeService taskNodeService;
    @Autowired
    private MainAndMonitorDateManager mainAndMonitorDateManager;
    
	@ApiOperation(value = "统计7天数据", notes = ""
			+ "1、TOTAL_TASKNUM:车辆任务数图表--:DATE：时间、TASK_VALUE：每日任务总数值、TASK_UNUSUAL_VALUE：每日异常总数值、VEHICLE_AVG_NUM：单车平均任务数<br/>"
			+ "2、TOTAL_MILEAGE:每日车辆总里程图表；DATE：时间；VALUE：值；<br/>"
			+ "3、TOTAL_FUEL:每日车辆总油耗图表；DATE：时间；VALUE：值；<br/>"
			+ "4、UTILIZATION_RATIO:车辆使用率图表；DATE：时间；VALUE：值；<br/>")
	@RequestMapping(value = { "/getVehicleDataByDay" }, method = RequestMethod.GET)
	public ResultModel getVehicleDataByDay(){
		 ResultModel model = new ResultModel();
		 model.setCode(0);
		 Map<String, Object> resultMap = null;
	        try {
	        	//查询redis得到统计车辆的数据
	        	resultMap = mainAndMonitorDateManager.getVehicleDataByDay();
	        	//数据为空
	            if(resultMap ==null && resultMap.toString() =="{}"){
	            	//直接查询数据库
	            	resultMap = mainService.getVehicleDataByDay();
	            }
	            model.setSub_code(0);
	            model.setData(new JSONObject().fluentPut("result", resultMap != null ? resultMap : new HashMap<String, Object>()));
	        }catch (Exception e){
	        	model.setSub_code(0);
	        	// 返回空值的天数列表
				model.setData(new JSONObject().fluentPut("result", mainService.getVehicleDataForDay()));
	            logger.error("首页统计数据出错！", e);
	        }
	        return model;
	}
	
    @ApiOperation(value = "统计任务数据（首页重点指标值）", notes = ""
			+ "1、TASK_NUM:当前任务总数<br/>"
			+ "2、EXECUT_STATE:执行中任务数<br/>"
			+ "3、TOBE_COMPLETED:待完成任务数<br/>"
			+ "4、TASK_UNUSUAL_NUM:每日异常任务数<br/>")
	@RequestMapping(value = { "/getTaskDataByDay" }, method = RequestMethod.GET)
	public ResultModel getTaskDataByDay(){
		 ResultModel model = new ResultModel();
		 model.setCode(0);
		 Map<String, Object> resultMap = null;
	        try {
	            resultMap = mainService.getTaskDataByDay();
	            model.setSub_code(0);
	            model.setData(new JSONObject().fluentPut("result", resultMap));
	        }catch (Exception e){
	        	 model.setSub_code(1);
	            logger.error("运输任务列表查询出错！", e);
	        }
	        return model;
	}
	
    @ApiOperation(value = "监控大屏根据车辆查询所有任务（执行中和已完成的）")
    @RequestMapping(value = "/listAllTaskOnScreen", method = { RequestMethod.POST })
    public ResultModel listAllTaskOnScreen(TaskGirdQuery queryParam) {
        ResultModel model = new ResultModel();
        model.setCode(0);
        try {
        	int start = queryParam.getPageNo();
        	int end = queryParam.getPageSize();
        	start = (start-1) * end;
        	end = (queryParam.getPageNo()) * end;
        	String string = mainAndMonitorDateManager.getAllScreenTask(start, end);
        	List<TaskScreenVO> list = JSONArray.parseArray(string, TaskScreenVO.class);
        	if(list !=null || string !="{}"){
        		queryParam.setCount(mainAndMonitorDateManager.getAllScreenTaskSize());
        	}else{
        		list = taskService.listAllTaskOnScreen(queryParam);
        	}
        	//List<TaskScreenVO> list = taskService.listAllTaskOnScreen(queryParam);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", list));
            model.setPage(queryParam);
        }catch (Exception e){
			model.setSub_code(0);
			model.setData(new JSONObject().fluentPut("result", new ArrayList<>()));
			logger.error("监控大屏根据车辆查询所有任务出错！", e);
        }
        return model;
    }
	
    @ApiOperation(value = "根据任务ID查询任务明细详情",notes="包含--"
    		+ "任务基本信息task，<br/>"
    		+ "任务异常事件列表eventList，<br/>"
    		+ "任务的物料订单明细列表orderList，<br/>"
    		+ "任务节点列表nodeList，<br/>"
    		+ "订单所含有的装货站点列表taskBranchList")
    @RequestMapping(value = "/getTaskDetailByTaskId/{taskId}", method = { RequestMethod.GET })
    @ApiImplicitParam(paramType = "path", name = "taskId", value = "运输任务ID", dataType = "Long", required = true)
    public ResultModel getTaskDetailByTaskId(@PathVariable Long taskId) {
    	ResultModel model = null;
		try {
			// 1、任务对象
			TaskVO task = taskService.getTaskVOByTaskId(taskId);
			// 2、订单和订单对应的物料明细
			List<OrderVO> orderList = orderService.listOrderByTaskId(taskId);
        	for (OrderVO orderVO : orderList) {
        		// 物料明细
        		List<OrderDetailVO> list = orderService.listOrderDetailByOrderIdOrOrderNo(orderVO.getId(), null);
        		orderVO.setOrderDetailList(list);
			}
        	// 3、异常任务事件列表
        	List<TaskEventVO> eventList = taskEventService.getTaskEventList(taskId);
        	// 4、查询任务节点列表
        	List<TaskNodeVO> nodeList = taskNodeService.getTaskNodeList(taskId);
        	for (TaskNodeVO taskNodeVO : nodeList) {
				if(taskNodeVO.getNodeType() ==20 || taskNodeVO.getNodeType() ==21){
					List<TaskMaterielVO> list = taskNodeService.getTaskMaterielListByNodeId(taskNodeVO.getId());
					if(list.size() >0){
						taskNodeVO.setGoods(list);
					}
				}
			}
        	// 5、订单所含有的站点列表
        	List<TaskBranchVO> branchList = taskService.getTaskBranchList(taskId);
        	TaskDetailVO taskDetail = new TaskDetailVO();
        	taskDetail.setTaskVO(task);
        	taskDetail.setOrderList(orderList);
        	taskDetail.setEventList(eventList);
        	taskDetail.setNodeList(nodeList);
        	taskDetail.setTaskBranchList(branchList);
        	model =  new ResultModel(0, 0, new JSONObject().fluentPut("result" , taskDetail));
        }catch (Exception e){
        	e.printStackTrace();
        	logger.error("根据任务ID查询任务明细详情！id：" + taskId, e);
        }
        return model;
    }
    
	@ApiOperation(value = "根据任务ID查询任务货物明细")
    @RequestMapping(value = "/getOrderDetailByTaskId/{taskId}", method = { RequestMethod.GET })
    @ApiImplicitParam(paramType = "path", name = "taskId", value = "运输任务ID", dataType = "Long", required = true)
    public ResultModel getOrderDetailByTaskId(@PathVariable Long taskId) {
    	ResultModel model = new ResultModel();
    	List<Map<String, Object>> list = new ArrayList<>();
    	try {
    		String string = mainAndMonitorDateManager.getListOrderDetailByTaskId(taskId.toString());
    		List<Object> listObj = JSONObject.parseArray(string, Object.class);
    		if(listObj !=null || string !="{}"){
    			for(Object obj : listObj){
    			     Map<String, Object> item = (Map<String, Object>) obj;
    			     list.add(item);
    			}
    		}
    		if(list ==null)list = taskService.listOrderDetailByTaskId(taskId);
            model.setCode(0);
            model.setSub_code(0);
            model.setData(new JSONObject().fluentPut("result", list));
        }catch (Exception e){
        	model.setSub_code(1);
       	 	model.setData(new JSONObject().fluentPut("result", list));
            logger.error("通过任务id查询货物明细接口异常！", e);
        }
        return model;
    }
    
    @ApiOperation(value = "获取服务时间")
    @RequestMapping(value = "/getServerDateTime", method = { RequestMethod.GET })
    public ResultModel getServerDateTime() {
        ResultModel model = new ResultModel();
        Date date= new Date();
        model.setCode(0);
		try {
			model.setSub_code(0);
			model.setData(new JSONObject().fluentPut("result", date.getTime()));
		} catch (Exception e) {
			model.setSub_code(1);
			model.setData(new JSONObject().fluentPut("result", date.getTime()));
			logger.error("获取服务时间出错！", e);
		}
        return model;
    }
}
